<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>promise的含义 | GS0401</title><meta name="author" content="John Doe"><meta name="copyright" content="John Doe"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="1.promise的含义Promise 是异步编程的一种解决方案，比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现，ES6 将其写进了语言标准，统一了用法，原生提供了Promise对象。 所谓Promise，简单说就是一个容器，里面保存着某个未来才会结束的事件（通常是一个异步操作）的结果。从语法上说，Promise 是一个对象，从它可以获取异步操作的消息。Promise">
<meta property="og:type" content="article">
<meta property="og:title" content="promise的含义">
<meta property="og:url" content="http://example.com/2022/05/27/ss/promise/index.html">
<meta property="og:site_name" content="GS0401">
<meta property="og:description" content="1.promise的含义Promise 是异步编程的一种解决方案，比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现，ES6 将其写进了语言标准，统一了用法，原生提供了Promise对象。 所谓Promise，简单说就是一个容器，里面保存着某个未来才会结束的事件（通常是一个异步操作）的结果。从语法上说，Promise 是一个对象，从它可以获取异步操作的消息。Promise">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="">
<meta property="article:published_time" content="2022-05-27T10:50:00.000Z">
<meta property="article:modified_time" content="2022-05-29T03:42:12.918Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content=""><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2022/05/27/ss/promise/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'promise的含义',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-29 11:42:12'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">GS0401</a></span><div id="menus"><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">promise的含义</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-27T10:50:00.000Z" title="发表于 2022-05-27 18:50:00">2022-05-27</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-29T03:42:12.918Z" title="更新于 2022-05-29 11:42:12">2022-05-29</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="promise的含义"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="1-promise的含义"><a href="#1-promise的含义" class="headerlink" title="1.promise的含义"></a>1.promise的含义</h2><p>Promise 是异步编程的一种解决方案，比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现，ES6 将其写进了语言标准，统一了用法，原生提供了Promise对象。</p>
<p>所谓Promise，简单说就是一个容器，里面保存着某个未来才会结束的事件（通常是一个异步操作）的结果。从语法上说，Promise 是一个对象，从它可以获取异步操作的消息。Promise 提供统一的 API，各种异步操作都可以用同样的方法进行处理。</p>
<h4 id="Promise对象有以下两个特点"><a href="#Promise对象有以下两个特点" class="headerlink" title="Promise对象有以下两个特点"></a>Promise对象有以下两个特点</h4><p>（1）对象的状态不受外界影响。Promise对象代表一个异步操作，有三种状态：pending（进行中）、fulfilled（已成功）和rejected（已失败）。只有异步操作的结果，可以决定当前是哪一种状态，任何其他操作都无法改变这个状态。这也是Promise这个名字的由来，它的英语意思就是“承诺”，表示其他手段无法改变。</p>
<p>（2）一旦状态改变，就不会再变，任何时候都可以得到这个结果。Promise对象的状态改变，只有两种可能：从pending变为fulfilled和从pending变为rejected。只要这两种情况发生，状态就凝固了，不会再变了，会一直保持这个结果，这时就称为 resolved（已定型）。如果改变已经发生了，你再对Promise对象添加回调函数，也会立即得到这个结果。这与事件（Event）完全不同，事件的特点是，如果你错过了它，再去监听，是得不到结果的。</p>
<p>有了Promise对象，就可以将异步操作以同步操作的流程表达出来，避免了层层嵌套的回调函数。此外，Promise对象提供统一的接口，使得控制异步操作更加容易。</p>
<p>Promise也有一些缺点。首先，无法取消Promise，一旦新建它就会立即执行，无法中途取消。其次，如果不设置回调函数，Promise内部抛出的错误，不会反应到外部。第三，当处于pending状态时，无法得知目前进展到哪一个阶段（刚刚开始还是即将完成）。</p>
<p>如果某些事件不断地反复发生，一般来说，使用 Stream 模式是比部署Promise更好的选择。</p>
<h2 id="2-基本用法"><a href="#2-基本用法" class="headerlink" title="2.基本用法"></a>2.基本用法</h2><p>ES6 规定，Promise对象是一个构造函数，用来生成Promise实例。</p>
<p>下面代码创造了一个Promise实例。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">const promise = new Promise(<span class="keyword">function</span>(resolve, reject) &#123;</span><br><span class="line">  // ... some code</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (/* 异步操作成功 */)&#123;</span><br><span class="line">    resolve(value);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    reject(error);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Promise构造函数接受一个函数作为参数，该函数的两个参数分别是resolve和reject。它们是两个函数，由 JavaScript 引擎提供，不用自己部署。</p>
<p>resolve函数的作用是，将Promise对象的状态从“未完成”变为“成功”（即从 pending 变为 resolved），在异步操作成功时调用，并将异步操作的结果，作为参数传递出去；reject函数的作用是，将Promise对象的状态从“未完成”变为“失败”（即从 pending 变为 rejected），在异步操作失败时调用，并将异步操作报出的错误，作为参数传递出去。</p>
<p>Promise实例生成以后，可以用then方法分别指定resolved状态和rejected状态的回调函数。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">promise.then(<span class="keyword">function</span>(value) &#123;</span><br><span class="line">  // success</span><br><span class="line">&#125;, <span class="keyword">function</span>(error) &#123;</span><br><span class="line">  // failure</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用，第二个回调函数是Promise对象的状态变为rejected时调用。这两个函数都是可选的，不一定要提供。它们都接受Promise对象传出的值作为参数。</p>
<p>下面是一个Promise对象的简单例子。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="built_in">timeout</span>(ms) &#123;</span><br><span class="line">  <span class="built_in">return</span> new Promise((resolve, reject) =&gt; &#123;</span><br><span class="line">    setTimeout(resolve, ms, <span class="string">&#x27;done&#x27;</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">timeout</span>(100).<span class="keyword">then</span>((value) =&gt; &#123;</span><br><span class="line">  console.log(value);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>上面代码中，timeout方法返回一个Promise实例，表示一段时间以后才会发生的结果。过了指定的时间（ms参数）以后，Promise实例的状态变为resolved，就会触发then方法绑定的回调函数。<br>Promise 新建后就会立即执行。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> promise = new Promise(<span class="keyword">function</span>(resolve, reject) &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;Promise&#x27;</span>);</span><br><span class="line">  resolve();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">promise.then(<span class="function"><span class="title">function</span></span>() &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;resolved.&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">console.log(<span class="string">&#x27;Hi!&#x27;</span>);</span><br><span class="line"></span><br><span class="line">// Promise</span><br><span class="line">// Hi!</span><br><span class="line">// resolved</span><br></pre></td></tr></table></figure>

<p>上面代码中，Promise 新建后立即执行，所以首先输出的是Promise。然后，then方法指定的回调函数，将在当前脚本所有同步任务执行完才会执行，所以resolved最后输出。</p>
<p>下面是异步加载图片的例子。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> promise = new Promise(<span class="keyword">function</span>(resolve, reject) &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;Promise&#x27;</span>);</span><br><span class="line">  resolve();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">promise.then(<span class="function"><span class="title">function</span></span>() &#123;</span><br><span class="line"><span class="keyword">function</span> loadImageAsync(url) &#123;</span><br><span class="line">  <span class="built_in">return</span> new Promise(<span class="keyword">function</span>(resolve, reject) &#123;</span><br><span class="line">    const image = new Image();</span><br><span class="line"></span><br><span class="line">    image.onload = <span class="function"><span class="title">function</span></span>() &#123;</span><br><span class="line">      resolve(image);</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    image.onerror = <span class="function"><span class="title">function</span></span>() &#123;</span><br><span class="line">      reject(new Error(<span class="string">&#x27;Could not load image at &#x27;</span> + url));</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    image.src = url;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面代码中，使用Promise包装了一个图片加载的异步操作。如果加载成功，就调用resolve方法，否则就调用reject方法。</p>
<p>下面是一个用Promise对象实现的 Ajax 操作的例子。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">const getJSON = <span class="keyword">function</span>(url) &#123;</span><br><span class="line">  const promise = new Promise(<span class="keyword">function</span>(resolve, reject)&#123;</span><br><span class="line">    const handler = <span class="function"><span class="title">function</span></span>() &#123;</span><br><span class="line">      <span class="keyword">if</span> (this.readyState !== 4) &#123;</span><br><span class="line">        <span class="built_in">return</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (this.status === 200) &#123;</span><br><span class="line">        resolve(this.response);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        reject(new Error(this.statusText));</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    const client = new XMLHttpRequest();</span><br><span class="line">    client.open(<span class="string">&quot;GET&quot;</span>, url);</span><br><span class="line">    client.onreadystatechange = handler;</span><br><span class="line">    client.responseType = <span class="string">&quot;json&quot;</span>;</span><br><span class="line">    client.setRequestHeader(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span><br><span class="line">    client.send();</span><br><span class="line"></span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="built_in">return</span> promise;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">getJSON(<span class="string">&quot;/posts.json&quot;</span>).<span class="keyword">then</span>(<span class="keyword">function</span>(json) &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;Contents: &#x27;</span> + json);</span><br><span class="line">&#125;, <span class="keyword">function</span>(error) &#123;</span><br><span class="line">  console.error(<span class="string">&#x27;出错了&#x27;</span>, error);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，getJSON是对 XMLHttpRequest 对象的封装，用于发出一个针对 JSON 数据的 HTTP 请求，并且返回一个Promise对象。需要注意的是，在getJSON内部，resolve函数和reject函数调用时，都带有参数。</p>
<p>如果调用resolve函数和reject函数时带有参数，那么它们的参数会被传递给回调函数。reject函数的参数通常是Error对象的实例，表示抛出的错误；resolve函数的参数除了正常的值以外，还可能是另一个 Promise 实例，比如像下面这样。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">const p1 = new Promise(<span class="keyword">function</span> (resolve, reject) &#123;</span><br><span class="line">  setTimeout(() =&gt; reject(new Error(<span class="string">&#x27;fail&#x27;</span>)), 3000)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">const p2 = new Promise(<span class="keyword">function</span> (resolve, reject) &#123;</span><br><span class="line">  setTimeout(() =&gt; resolve(p1), 1000)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">p2</span><br><span class="line">  .<span class="keyword">then</span>(result =&gt; console.log(result))</span><br><span class="line">  .catch(error =&gt; console.log(error))</span><br><span class="line">// Error: fail</span><br></pre></td></tr></table></figure>

<p>上面代码中，p1是一个 Promise，3 秒之后变为rejected。p2的状态在 1 秒之后改变，resolve方法返回的是p1。由于p2返回的是另一个 Promise，导致p2自己的状态无效了，由p1的状态决定p2的状态。所以，后面的then语句都变成针对后者（p1）。又过了 2 秒，p1变为rejected，导致触发catch方法指定的回调函数。</p>
<p>注意，调用resolve或reject并不会终结 Promise 的参数函数的执行。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">new Promise((resolve, reject) =&gt; &#123;</span><br><span class="line">  resolve(1);</span><br><span class="line">  console.log(2);</span><br><span class="line">&#125;).<span class="keyword">then</span>(r =&gt; &#123;</span><br><span class="line">  console.log(r);</span><br><span class="line">&#125;);</span><br><span class="line">// 2</span><br><span class="line">// 1</span><br></pre></td></tr></table></figure>

<p>上面代码中，调用resolve(1)以后，后面的console.log(2)还是会执行，并且会首先打印出来。这是因为立即 resolved 的 Promise 是在本轮事件循环的末尾执行，总是晚于本轮循环的同步任务。</p>
<p>一般来说，调用resolve或reject以后，Promise 的使命就完成了，后继操作应该放到then方法里面，而不应该直接写在resolve或reject的后面。所以，最好在它们前面加上return语句，这样就不会有意外。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">new Promise((resolve, reject) =&gt; &#123;</span><br><span class="line">  <span class="built_in">return</span> resolve(1);</span><br><span class="line">  // 后面的语句不会执行</span><br><span class="line">  console.log(2);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="3-promise-prototype-then"><a href="#3-promise-prototype-then" class="headerlink" title="3.promise.prototype.then"></a>3.promise.prototype.then</h2><p>Promise 实例具有then方法，也就是说，then方法是定义在原型对象Promise.prototype上的。它的作用是为 Promise 实例添加状态改变时的回调函数。前面说过，then方法的第一个参数是resolved状态的回调函数，第二个参数是rejected状态的回调函数，它们都是可选的。</p>
<p>then方法返回的是一个新的Promise实例（注意，不是原来那个Promise实例）。因此可以采用链式写法，即then方法后面再调用另一个then方法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">getJSON(<span class="string">&quot;/posts.json&quot;</span>).<span class="keyword">then</span>(<span class="keyword">function</span>(json) &#123;</span><br><span class="line">  <span class="built_in">return</span> json.post;</span><br><span class="line">&#125;).<span class="keyword">then</span>(<span class="keyword">function</span>(post) &#123;</span><br><span class="line">  // ...</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>上面的代码使用then方法，依次指定了两个回调函数。第一个回调函数完成以后，会将返回结果作为参数，传入第二个回调函数。</p>
<p>采用链式的then，可以指定一组按照次序调用的回调函数。这时，前一个回调函数，有可能返回的还是一个Promise对象（即有异步操作），这时后一个回调函数，就会等待该Promise对象的状态发生变化，才会被调用。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">getJSON(<span class="string">&quot;/post/1.json&quot;</span>).<span class="keyword">then</span>(<span class="keyword">function</span>(post) &#123;</span><br><span class="line">  <span class="built_in">return</span> getJSON(post.commentURL);</span><br><span class="line">&#125;).<span class="keyword">then</span>(<span class="keyword">function</span> (comments) &#123;</span><br><span class="line">  console.log(<span class="string">&quot;resolved: &quot;</span>, comments);</span><br><span class="line">&#125;, <span class="keyword">function</span> (err)&#123;</span><br><span class="line">  console.log(<span class="string">&quot;rejected: &quot;</span>, err);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>上面代码中，第一个then方法指定的回调函数，返回的是另一个Promise对象。这时，第二个then方法指定的回调函数，就会等待这个新的Promise对象状态发生变化。如果变为resolved，就调用第一个回调函数，如果状态变为rejected，就调用第二个回调函数。</p>
<p>如果采用箭头函数，上面的代码可以写得更简洁。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">getJSON(<span class="string">&quot;/post/1.json&quot;</span>).<span class="keyword">then</span>(</span><br><span class="line">  post =&gt; getJSON(post.commentURL)</span><br><span class="line">).<span class="keyword">then</span>(</span><br><span class="line">  comments =&gt; console.log(<span class="string">&quot;resolved: &quot;</span>, comments),</span><br><span class="line">  err =&gt; console.log(<span class="string">&quot;rejected: &quot;</span>, err)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>


<h2 id="4-Promise-prototype-catch"><a href="#4-Promise-prototype-catch" class="headerlink" title="4.Promise.prototype.catch"></a>4.Promise.prototype.catch</h2><p>Promise.prototype.catch()方法是.then(null, rejection)或.then(undefined, rejection)的别名，用于指定发生错误时的回调函数。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">getJSON(<span class="string">&#x27;/posts.json&#x27;</span>).<span class="keyword">then</span>(<span class="keyword">function</span>(posts) &#123;</span><br><span class="line">  // ...</span><br><span class="line">&#125;).catch(<span class="keyword">function</span>(error) &#123;</span><br><span class="line">  // 处理 getJSON 和 前一个回调函数运行时发生的错误</span><br><span class="line">  console.log(<span class="string">&#x27;发生错误！&#x27;</span>, error);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="5-Promise-prototype-finally"><a href="#5-Promise-prototype-finally" class="headerlink" title="5.Promise.prototype.finally()"></a>5.Promise.prototype.finally()</h2><p>finally()方法用于指定不管 Promise 对象最后状态如何，都会执行的操作。该方法是 ES2018 引入标准的。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">promise</span><br><span class="line">.<span class="keyword">then</span>(result =&gt; &#123;···&#125;)</span><br><span class="line">.catch(error =&gt; &#123;···&#125;)</span><br><span class="line">.finally(() =&gt; &#123;···&#125;);</span><br></pre></td></tr></table></figure>


<p>上面代码中，不管promise最后的状态，在执行完then或catch指定的回调函数以后，都会执行finally方法指定的回调函数。</p>
<h2 id="6-Promise-all"><a href="#6-Promise-all" class="headerlink" title="6.Promise.all()"></a>6.Promise.all()</h2><p>Promise.all()方法用于将多个 Promise 实例，包装成一个新的 Promise 实例。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">const p = Promise.all([p1, p2, p3]);</span><br></pre></td></tr></table></figure>

<p>上面代码中，Promise.all()方法接受一个数组作为参数，p1、p2、p3都是 Promise 实例，如果不是，就会先调用下面讲到的Promise.resolve方法，将参数转为 Promise 实例，再进一步处理。另外，Promise.all()方法的参数可以不是数组，但必须具有 Iterator 接口，且返回的每个成员都是 Promise 实例。</p>
<p>p的状态由p1、p2、p3决定，分成两种情况。</p>
<p>（1）只有p1、p2、p3的状态都变成fulfilled，p的状态才会变成fulfilled，此时p1、p2、p3的返回值组成一个数组，传递给p的回调函数。</p>
<p>（2）只要p1、p2、p3之中有一个被rejected，p的状态就变成rejected，此时第一个被reject的实例的返回值，会传递给p的回调函数。</p>
<h2 id="7-Promise-race"><a href="#7-Promise-race" class="headerlink" title="7.Promise.race()"></a>7.Promise.race()</h2><p>Promise.race()方法同样是将多个 Promise 实例，包装成一个新的 Promise 实例。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">const p = Promise.race([p1, p2, p3]);</span><br></pre></td></tr></table></figure>
<p>上面代码中，只要p1、p2、p3之中有一个实例率先改变状态，p的状态就跟着改变。那个率先改变的 Promise 实例的返回值，就传递给p的回调函数。</p>
<p>Promise.race()方法的参数与Promise.all()方法一样，如果不是 Promise 实例，就会先调用下面讲到的Promise.resolve()方法，将参数转为 Promise 实例，再进一步处理。</p>
<p>下面是一个例子，如果指定时间内没有获得结果，就将 Promise 的状态变为reject，否则变为resolve。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">const p = Promise.race([</span><br><span class="line">  fetch(<span class="string">&#x27;/resource-that-may-take-a-while&#x27;</span>),</span><br><span class="line">  new Promise(<span class="keyword">function</span> (resolve, reject) &#123;</span><br><span class="line">    setTimeout(() =&gt; reject(new Error(<span class="string">&#x27;request timeout&#x27;</span>)), 5000)</span><br><span class="line">  &#125;)</span><br><span class="line">]);</span><br><span class="line"></span><br><span class="line">p</span><br><span class="line">.<span class="keyword">then</span>(console.log)</span><br><span class="line">.catch(console.error);</span><br></pre></td></tr></table></figure>

<p>上面代码中，如果 5 秒之内fetch方法无法返回结果，变量p的状态就会变为rejected，从而触发catch方法指定的回调函数。</p>
<h2 id="8-Promise-allSettled"><a href="#8-Promise-allSettled" class="headerlink" title="8.Promise.allSettled()"></a>8.Promise.allSettled()</h2><p>有时候，我们希望等到一组异步操作都结束了，不管每一个操作是成功还是失败，再进行下一步操作。但是，现有的 Promise 方法很难实现这个要求。</p>
<p>Promise.all()方法只适合所有异步操作都成功的情况，如果有一个操作失败，就无法满足要求。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">const urls = [url_1, url_2, url_3];</span><br><span class="line">const requests = urls.map(x =&gt; fetch(x));</span><br><span class="line"></span><br><span class="line">try &#123;</span><br><span class="line">  await Promise.all(requests);</span><br><span class="line">  console.log(<span class="string">&#x27;所有请求都成功。&#x27;</span>);</span><br><span class="line">&#125; catch &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;至少一个请求失败，其他请求可能还没结束。&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面示例中，Promise.all()可以确定所有请求都成功了，但是只要有一个请求失败，它就会报错，而不管另外的请求是否结束。</p>
<h2 id="9-Promise-any"><a href="#9-Promise-any" class="headerlink" title="9.Promise.any()"></a>9.Promise.any()</h2><p>ES2021 引入了Promise.any()方法。该方法接受一组 Promise 实例作为参数，包装成一个新的 Promise 实例返回。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Promise.any([</span><br><span class="line">  fetch(<span class="string">&#x27;https://v8.dev/&#x27;</span>).<span class="keyword">then</span>(() =&gt; <span class="string">&#x27;home&#x27;</span>),</span><br><span class="line">  fetch(<span class="string">&#x27;https://v8.dev/blog&#x27;</span>).<span class="keyword">then</span>(() =&gt; <span class="string">&#x27;blog&#x27;</span>),</span><br><span class="line">  fetch(<span class="string">&#x27;https://v8.dev/docs&#x27;</span>).<span class="keyword">then</span>(() =&gt; <span class="string">&#x27;docs&#x27;</span>)</span><br><span class="line">]).<span class="keyword">then</span>((first) =&gt; &#123;  // 只要有一个 fetch() 请求成功</span><br><span class="line">  console.log(first);</span><br><span class="line">&#125;).catch((error) =&gt; &#123; // 所有三个 fetch() 全部请求失败</span><br><span class="line">  console.log(error);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>只要参数实例有一个变成fulfilled状态，包装实例就会变成fulfilled状态；如果所有参数实例都变成rejected状态，包装实例就会变成rejected状态。</p>
<p>Promise.any()跟Promise.race()方法很像，只有一点不同，就是Promise.any()不会因为某个 Promise 变成rejected状态而结束，必须等到所有参数 Promise 变成rejected状态才会结束。</p>
<h2 id="10-Promise-resolve"><a href="#10-Promise-resolve" class="headerlink" title="10.Promise.resolve()"></a>10.Promise.resolve()</h2><p>有时需要将现有对象转为 Promise 对象，Promise.resolve()方法就起到这个作用。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">const jsPromise = Promise.resolve($.ajax(<span class="string">&#x27;/whatever.json&#x27;</span>));</span><br></pre></td></tr></table></figure>
<p>上面代码将 jQuery 生成的deferred对象，转为一个新的 Promise 对象。</p>
<p>Promise.resolve()等价于下面的写法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Promise.resolve(<span class="string">&#x27;foo&#x27;</span>)</span><br><span class="line">// 等价于</span><br><span class="line">new Promise(resolve =&gt; resolve(<span class="string">&#x27;foo&#x27;</span>))</span><br></pre></td></tr></table></figure>

<p>Promise.resolve()方法的参数分成四种情况。</p>
<h4 id="（1）参数是一个-Promise-实例"><a href="#（1）参数是一个-Promise-实例" class="headerlink" title="（1）参数是一个 Promise 实例"></a>（1）参数是一个 Promise 实例</h4><p>如果参数是 Promise 实例，那么Promise.resolve将不做任何修改、原封不动地返回这个实例。</p>
<h4 id="（2）参数是一个thenable对象"><a href="#（2）参数是一个thenable对象" class="headerlink" title="（2）参数是一个thenable对象"></a>（2）参数是一个thenable对象</h4><p>thenable对象指的是具有then方法的对象，比如下面这个对象。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> thenable = &#123;</span><br><span class="line">  <span class="keyword">then</span>: <span class="keyword">function</span>(resolve, reject) &#123;</span><br><span class="line">    resolve(42);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>Promise.resolve()方法会将这个对象转为 Promise 对象，然后就立即执行thenable对象的then()方法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> thenable = &#123;</span><br><span class="line">  <span class="keyword">then</span>: <span class="keyword">function</span>(resolve, reject) &#123;</span><br><span class="line">    resolve(42);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="built_in">let</span> p1 = Promise.resolve(thenable);</span><br><span class="line">p1.then(<span class="keyword">function</span> (value) &#123;</span><br><span class="line">  console.log(value);  // 42</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>上面代码中，thenable对象的then()方法执行后，对象p1的状态就变为resolved，从而立即执行最后那个then()方法指定的回调函数，输出42。</p>
<h4 id="（3）参数不是具有then-方法的对象，或根本就不是对象"><a href="#（3）参数不是具有then-方法的对象，或根本就不是对象" class="headerlink" title="（3）参数不是具有then()方法的对象，或根本就不是对象"></a>（3）参数不是具有then()方法的对象，或根本就不是对象</h4><p>如果参数是一个原始值，或者是一个不具有then()方法的对象，则Promise.resolve()方法返回一个新的 Promise 对象，状态为resolved。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">const p = Promise.resolve(<span class="string">&#x27;Hello&#x27;</span>);</span><br><span class="line"></span><br><span class="line">p.then(<span class="keyword">function</span> (s) &#123;</span><br><span class="line">  console.log(s)</span><br><span class="line">&#125;);</span><br><span class="line">// Hello</span><br></pre></td></tr></table></figure>

<p>上面代码生成一个新的 Promise 对象的实例p。由于字符串Hello不属于异步操作（判断方法是字符串对象不具有 then 方法），返回 Promise 实例的状态从一生成就是resolved，所以回调函数会立即执行。Promise.resolve()方法的参数，会同时传给回调函数。</p>
<h4 id="（4）不带有任何参数"><a href="#（4）不带有任何参数" class="headerlink" title="（4）不带有任何参数"></a>（4）不带有任何参数</h4><p>Promise.resolve()方法允许调用时不带参数，直接返回一个resolved状态的 Promise 对象。</p>
<p>所以，如果希望得到一个 Promise 对象，比较方便的方法就是直接调用Promise.resolve()方法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">const p = Promise.resolve();</span><br><span class="line"></span><br><span class="line">p.then(<span class="function"><span class="title">function</span></span> () &#123;</span><br><span class="line">  // ...</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>上面代码的变量p就是一个 Promise 对象。</p>
<p>需要注意的是，立即resolve()的 Promise 对象，是在本轮“事件循环”（event loop）的结束时执行，而不是在下一轮“事件循环”的开始时。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">setTimeout(<span class="function"><span class="title">function</span></span> () &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;three&#x27;</span>);</span><br><span class="line">&#125;, 0);</span><br><span class="line"></span><br><span class="line">Promise.resolve().<span class="keyword">then</span>(<span class="function"><span class="title">function</span></span> () &#123;</span><br><span class="line">  console.log(<span class="string">&#x27;two&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">console.log(<span class="string">&#x27;one&#x27;</span>);</span><br><span class="line"></span><br><span class="line">// one</span><br><span class="line">// two</span><br><span class="line">// three</span><br></pre></td></tr></table></figure>

<p>上面代码中，setTimeout(fn, 0)在下一轮“事件循环”开始时执行，Promise.resolve()在本轮“事件循环”结束时执行，console.log(‘one’)则是立即执行，因此最先输出。</p>
<h2 id="11-Promise-reject"><a href="#11-Promise-reject" class="headerlink" title="11.Promise.reject()"></a>11.Promise.reject()</h2><p>Promise.reject(reason)方法也会返回一个新的 Promise 实例，该实例的状态为rejected。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">const p = Promise.reject(<span class="string">&#x27;出错了&#x27;</span>);</span><br><span class="line">// 等同于</span><br><span class="line">const p = new Promise((resolve, reject) =&gt; reject(<span class="string">&#x27;出错了&#x27;</span>))</span><br><span class="line"></span><br><span class="line">p.then(null, <span class="keyword">function</span> (s) &#123;</span><br><span class="line">  console.log(s)</span><br><span class="line">&#125;);</span><br><span class="line">// 出错了</span><br></pre></td></tr></table></figure>

<p>上面代码生成一个 Promise 对象的实例p，状态为rejected，回调函数会立即执行。</p>
<p>Promise.reject()方法的参数，会原封不动地作为reject的理由，变成后续方法的参数。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Promise.reject(<span class="string">&#x27;出错了&#x27;</span>)</span><br><span class="line">.catch(e =&gt; &#123;</span><br><span class="line">  console.log(e === <span class="string">&#x27;出错了&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">// <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<p>上面代码中，Promise.reject()方法的参数是一个字符串，后面catch()方法的参数e就是这个字符串。</p>
<h2 id="12-应用"><a href="#12-应用" class="headerlink" title="12.应用"></a>12.应用</h2><h4 id="加载图片"><a href="#加载图片" class="headerlink" title="加载图片"></a>加载图片</h4><p>我们可以将图片的加载写成一个Promise，一旦加载完成，Promise的状态就发生变化。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">const preloadImage = <span class="keyword">function</span> (path) &#123;</span><br><span class="line">  <span class="built_in">return</span> new Promise(<span class="keyword">function</span> (resolve, reject) &#123;</span><br><span class="line">    const image = new Image();</span><br><span class="line">    image.onload  = resolve;</span><br><span class="line">    image.onerror = reject;</span><br><span class="line">    image.src = path;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>Generator 函数与 Promise 的结合<br>使用 Generator 函数管理流程，遇到异步操作的时候，通常返回一个Promise对象。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="function"><span class="title">getFoo</span></span> () &#123;</span><br><span class="line">  <span class="built_in">return</span> new Promise(<span class="keyword">function</span> (resolve, reject)&#123;</span><br><span class="line">    resolve(<span class="string">&#x27;foo&#x27;</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const g = <span class="keyword">function</span>* () &#123;</span><br><span class="line">  try &#123;</span><br><span class="line">    const foo = yield getFoo();</span><br><span class="line">    console.log(foo);</span><br><span class="line">  &#125; catch (e) &#123;</span><br><span class="line">    console.log(e);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> run (generator) &#123;</span><br><span class="line">  const it = generator();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">function</span> go(result) &#123;</span><br><span class="line">    <span class="keyword">if</span> (result.done) <span class="built_in">return</span> result.value;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">return</span> result.value.then(<span class="keyword">function</span> (value) &#123;</span><br><span class="line">      <span class="built_in">return</span> go(it.next(value));</span><br><span class="line">    &#125;, <span class="keyword">function</span> (error) &#123;</span><br><span class="line">      <span class="built_in">return</span> go(it.throw(error));</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  go(it.next());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">run(g);</span><br></pre></td></tr></table></figure>

<p>上面代码的 Generator 函数g之中，有一个异步操作getFoo，它返回的就是一个Promise对象。函数run用来处理这个Promise对象，并调用下一个next方法。</p>
<h2 id="13-Promise-try"><a href="#13-Promise-try" class="headerlink" title="13.Promise.try()"></a>13.Promise.try()</h2><p>实际开发中，经常遇到一种情况：不知道或者不想区分，函数f是同步函数还是异步操作，但是想用 Promise 来处理它。因为这样就可以不管f是否包含异步操作，都用then方法指定下一步流程，用catch方法处理f抛出的错误。一般就会采用下面的写法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Promise.resolve().<span class="keyword">then</span>(f)</span><br></pre></td></tr></table></figure>

<p>上面的写法有一个缺点，就是如果f是同步函数，那么它会在本轮事件循环的末尾执行。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">const f = () =&gt; console.log(<span class="string">&#x27;now&#x27;</span>);</span><br><span class="line">Promise.resolve().<span class="keyword">then</span>(f);</span><br><span class="line">console.log(<span class="string">&#x27;next&#x27;</span>);</span><br><span class="line">// next</span><br><span class="line">// now</span><br></pre></td></tr></table></figure>

<p>上面代码中，函数f是同步的，但是用 Promise 包装了以后，就变成异步执行了。</p>
<p>那么有没有一种方法，让同步函数同步执行，异步函数异步执行，并且让它们具有统一的 API 呢？回答是可以的，并且还有两种写法。第一种写法是用async函数来写。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">const f = () =&gt; console.log(<span class="string">&#x27;now&#x27;</span>);</span><br><span class="line">(async () =&gt; f())();</span><br><span class="line">console.log(<span class="string">&#x27;next&#x27;</span>);</span><br><span class="line">// now</span><br><span class="line">// next</span><br></pre></td></tr></table></figure>

<p>上面代码中，第二行是一个立即执行的匿名函数，会立即执行里面的async函数，因此如果f是同步的，就会得到同步的结果；如果f是异步的，就可以用then指定下一步，就像下面的写法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">(async () =&gt; f())()</span><br><span class="line">.<span class="keyword">then</span>(...)</span><br></pre></td></tr></table></figure>

<p>需要注意的是，async () &#x3D;&gt; f()会吃掉f()抛出的错误。所以，如果想捕获错误，要使用promise.catch方法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">(async () =&gt; f())()</span><br><span class="line">.<span class="keyword">then</span>(...)</span><br><span class="line">.catch(...)</span><br></pre></td></tr></table></figure>

<p>第二种写法是使用new Promise()。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">const f = () =&gt; console.log(<span class="string">&#x27;now&#x27;</span>);</span><br><span class="line">(</span><br><span class="line">  () =&gt; new Promise(</span><br><span class="line">    resolve =&gt; resolve(f())</span><br><span class="line">  )</span><br><span class="line">)();</span><br><span class="line">console.log(<span class="string">&#x27;next&#x27;</span>);</span><br><span class="line">// now</span><br><span class="line">// next</span><br></pre></td></tr></table></figure>

<p>上面代码也是使用立即执行的匿名函数，执行new Promise()。这种情况下，同步函数也是同步执行的。</p>
<p>鉴于这是一个很常见的需求，所以现在有一个提案，提供Promise.try方法替代上面的写法。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">const f = () =&gt; console.log(<span class="string">&#x27;now&#x27;</span>);</span><br><span class="line">Promise.try(f);</span><br><span class="line">console.log(<span class="string">&#x27;next&#x27;</span>);</span><br><span class="line">// now</span><br><span class="line">// next</span><br></pre></td></tr></table></figure>

<p>事实上，Promise.try存在已久，Promise 库Bluebird、Q和when，早就提供了这个方法。</p>
<p>由于Promise.try为所有操作提供了统一的处理机制，所以如果想用then方法管理流程，最好都用Promise.try包装一下。这样有许多好处，其中一点就是可以更好地管理异常。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> getUsername(userId) &#123;</span><br><span class="line">  <span class="built_in">return</span> database.users.get(&#123;<span class="built_in">id</span>: userId&#125;)</span><br><span class="line">  .<span class="keyword">then</span>(<span class="keyword">function</span>(user) &#123;</span><br><span class="line">    <span class="built_in">return</span> user.name;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面代码中，database.users.get()返回一个 Promise 对象，如果抛出异步错误，可以用catch方法捕获，就像下面这样写。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">database.users.get(&#123;<span class="built_in">id</span>: userId&#125;)</span><br><span class="line">.<span class="keyword">then</span>(...)</span><br><span class="line">.catch(...)</span><br></pre></td></tr></table></figure>

<p>但是database.users.get()可能还会抛出同步错误（比如数据库连接错误，具体要看实现方法），这时你就不得不用try…catch去捕获。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">try &#123;</span><br><span class="line">  database.users.get(&#123;<span class="built_in">id</span>: userId&#125;)</span><br><span class="line">  .<span class="keyword">then</span>(...)</span><br><span class="line">  .catch(...)</span><br><span class="line">&#125; catch (e) &#123;</span><br><span class="line">  // ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面这样的写法就很笨拙了，这时就可以统一用promise.catch()捕获所有同步和异步的错误。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Promise.try(() =&gt; database.users.get(&#123;<span class="built_in">id</span>: userId&#125;))</span><br><span class="line">  .<span class="keyword">then</span>(...)</span><br><span class="line">  .catch(...)</span><br></pre></td></tr></table></figure>

<p>事实上，Promise.try就是模拟try代码块，就像promise.catch模拟的是catch代码块。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">John Doe</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2022/05/27/ss/promise/">http://example.com/2022/05/27/ss/promise/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">GS0401</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/gh/overtrue/share.js@master/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/05/27/hello-world/"><img class="prev-cover" src="" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Hello World</div></div></a></div><div class="next-post pull-right"><a href="/2022/05/27/ss/%E6%B0%B4%E4%BB%99%E8%8A%B1%E6%95%B0/"><img class="next-cover" src="" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">水仙花数</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">John Doe</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">27</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-promise%E7%9A%84%E5%90%AB%E4%B9%89"><span class="toc-number">1.</span> <span class="toc-text">1.promise的含义</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise%E5%AF%B9%E8%B1%A1%E6%9C%89%E4%BB%A5%E4%B8%8B%E4%B8%A4%E4%B8%AA%E7%89%B9%E7%82%B9"><span class="toc-number">1.0.1.</span> <span class="toc-text">Promise对象有以下两个特点</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"><span class="toc-number">2.</span> <span class="toc-text">2.基本用法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-promise-prototype-then"><span class="toc-number">3.</span> <span class="toc-text">3.promise.prototype.then</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-Promise-prototype-catch"><span class="toc-number">4.</span> <span class="toc-text">4.Promise.prototype.catch</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-Promise-prototype-finally"><span class="toc-number">5.</span> <span class="toc-text">5.Promise.prototype.finally()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-Promise-all"><span class="toc-number">6.</span> <span class="toc-text">6.Promise.all()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-Promise-race"><span class="toc-number">7.</span> <span class="toc-text">7.Promise.race()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-Promise-allSettled"><span class="toc-number">8.</span> <span class="toc-text">8.Promise.allSettled()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-Promise-any"><span class="toc-number">9.</span> <span class="toc-text">9.Promise.any()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-Promise-resolve"><span class="toc-number">10.</span> <span class="toc-text">10.Promise.resolve()</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%881%EF%BC%89%E5%8F%82%E6%95%B0%E6%98%AF%E4%B8%80%E4%B8%AA-Promise-%E5%AE%9E%E4%BE%8B"><span class="toc-number">10.0.1.</span> <span class="toc-text">（1）参数是一个 Promise 实例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E5%8F%82%E6%95%B0%E6%98%AF%E4%B8%80%E4%B8%AAthenable%E5%AF%B9%E8%B1%A1"><span class="toc-number">10.0.2.</span> <span class="toc-text">（2）参数是一个thenable对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%883%EF%BC%89%E5%8F%82%E6%95%B0%E4%B8%8D%E6%98%AF%E5%85%B7%E6%9C%89then-%E6%96%B9%E6%B3%95%E7%9A%84%E5%AF%B9%E8%B1%A1%EF%BC%8C%E6%88%96%E6%A0%B9%E6%9C%AC%E5%B0%B1%E4%B8%8D%E6%98%AF%E5%AF%B9%E8%B1%A1"><span class="toc-number">10.0.3.</span> <span class="toc-text">（3）参数不是具有then()方法的对象，或根本就不是对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%884%EF%BC%89%E4%B8%8D%E5%B8%A6%E6%9C%89%E4%BB%BB%E4%BD%95%E5%8F%82%E6%95%B0"><span class="toc-number">10.0.4.</span> <span class="toc-text">（4）不带有任何参数</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#11-Promise-reject"><span class="toc-number">11.</span> <span class="toc-text">11.Promise.reject()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-%E5%BA%94%E7%94%A8"><span class="toc-number">12.</span> <span class="toc-text">12.应用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8A%A0%E8%BD%BD%E5%9B%BE%E7%89%87"><span class="toc-number">12.0.1.</span> <span class="toc-text">加载图片</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#13-Promise-try"><span class="toc-number">13.</span> <span class="toc-text">13.Promise.try()</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/06/21/nginx%E7%9A%84%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8/" title="nginx的基础入门"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="nginx的基础入门"/></a><div class="content"><a class="title" href="/2022/06/21/nginx%E7%9A%84%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8/" title="nginx的基础入门">nginx的基础入门</a><time datetime="2022-06-20T23:49:26.000Z" title="发表于 2022-06-21 07:49:26">2022-06-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/06/21/vue3/" title="vue3"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="vue3"/></a><div class="content"><a class="title" href="/2022/06/21/vue3/" title="vue3">vue3</a><time datetime="2022-06-20T23:48:21.000Z" title="发表于 2022-06-21 07:48:21">2022-06-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/06/21/%E4%BD%BF%E7%94%A8%E5%88%86%E6%94%AF%E5%BC%80%E5%8F%91%E5%8A%9F%E8%83%BD%EF%BC%8C%E5%90%88%E5%B9%B6/" title="使用分支开发功能，合并"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="使用分支开发功能，合并"/></a><div class="content"><a class="title" href="/2022/06/21/%E4%BD%BF%E7%94%A8%E5%88%86%E6%94%AF%E5%BC%80%E5%8F%91%E5%8A%9F%E8%83%BD%EF%BC%8C%E5%90%88%E5%B9%B6/" title="使用分支开发功能，合并">使用分支开发功能，合并</a><time datetime="2022-06-20T23:47:54.000Z" title="发表于 2022-06-21 07:47:54">2022-06-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/06/21/git%E7%9A%84%E9%AB%98%E7%BA%A7%E6%93%8D%E4%BD%9C/" title="git的高级操作"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="git的高级操作"/></a><div class="content"><a class="title" href="/2022/06/21/git%E7%9A%84%E9%AB%98%E7%BA%A7%E6%93%8D%E4%BD%9C/" title="git的高级操作">git的高级操作</a><time datetime="2022-06-20T23:46:37.000Z" title="发表于 2022-06-21 07:46:37">2022-06-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/06/20/p10%E6%80%BB%E7%BB%93/" title="p10总结"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="p10总结"/></a><div class="content"><a class="title" href="/2022/06/20/p10%E6%80%BB%E7%BB%93/" title="p10总结">p10总结</a><time datetime="2022-06-20T08:54:35.000Z" title="发表于 2022-06-20 16:54:35">2022-06-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By John Doe</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>